###############################################################################
# Input: 
#  > landtagwahl2018_stimmbezirke.shp
#  > 08_arc_analyze/arc_input/treated_precincts.txt

# Output: 08_arc_analyze/arc_output/ltw18_sb_intersected.shp

#Task: Generate shape files of neighboring treated and control group precincts

###############################################################################

library(sf)
library(dplyr)

setwd("")

#pull shapefile
precincts <- st_read("02_rawdata/shp/landtagwahl2018_stimmbezirke.shp")

#dissolve not connected precincts
precincts <- precincts %>%
  group_by(LTW_SB_201) %>%
  summarize(geometry = st_union(geometry),
            .groups = 'drop')

#pull exported treatment
treatment <- read.csv("08_arc_analyze/arc_input/treated_precincts.txt", sep=",")

#join data
join_data <- inner_join(precincts, treatment, by = c("LTW_SB_201" = "sb_new"))

#divide by treatment
treated_precincts <- join_data[join_data$T==1,]
control_precincts <- join_data[join_data$T==0,]

# intersect treated and control group precincts
intersect_polygons <- st_intersection(treated_precincts, control_precincts)

# select line intersections only to define neighbors
ltw18_sb_intersected <- intersect_polygons %>%
  filter(st_geometry_type(.) %in% c("LINESTRING", "MULTILINESTRING", "POLYGON", "GEOMETRYCOLLECTION"))

# drop geography
ltw18_sb_intersected$geometry <- NULL

# rename
names(ltw18_sb_intersected) <- c("sb_new", "T", "sb_new_1", "T_1")

# export
write.csv(ltw18_sb_intersected, "08_arc_analyze/arc_output/ltw18_sb_intersected.txt", row.names = FALSE)
